import Taro from '@tarojs/taro'

const config = {
  baseURL: process.env.TARO_APP_API,
  timeout: 5000,
  header: { 'Content-Type': 'application/json' }
}

const requestInterceptor = (chain) => {
  const { requestParams } = chain
  const token = Taro.getStorageSync('token');
  if (token) { requestParams.header = { ...requestParams.header, 'Authorization': `Bearer ${token}` } }
  return chain.proceed(requestParams)
}

const responseInterceptor = async (chain) => {
  try {
    const res = await chain.proceed(chain.requestParams)
    if (res.statusCode >= 200 && res.statusCode < 300) { return res.data }
    return Promise.reject(`网络错误:${res.statusCode}`)
  } catch (error) {
    return Promise.reject(error)
  }
}

Taro.addInterceptor(requestInterceptor)
Taro.addInterceptor(responseInterceptor)

class Request {
  static async request(options) {
    try {
      const { url, ...rest } = options
      return await Taro.request({ url: `${config.baseURL}${url}`, ...config, ...rest })
    } catch (error) {
      console.log(error.message);
      Taro.showToast({ title: '请求失败', icon: 'none' })
      return Promise.reject(error)
    }
  }
  static get(url, data) { return this.request({ method: 'GET', url, data }) }
  static post(url, data) { return this.request({ method: 'POST', url, data }) }
}

export default Request
